package com.ls.lserp.modules.order.web;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.excel.ImportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.material.entity.InventoryRequestEx;
import com.ls.lserp.modules.material.service.InventoryRequestExService;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;
import com.ls.lserp.modules.order.service.CustomizationUnitCostService;
import com.ls.lserp.modules.sys.entity.SendEmailMessage;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import groovy.util.ResourceException;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import freemarker.template.Configuration;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.RequestContext;


@Controller
@RequestMapping(value = "${adminPath}/customization/unitcost")
public class CustomizationUnitCostController extends BaseController {

	@Autowired
	Configuration freemarkerConfiguration;

	@Autowired
	private CustomizationUnitCostService customizationUnitCostService;

	@Autowired
	private InventoryRequestExService inventoryRequestExService;

	/**
	 * 定制订单质检(订单查询)
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String customizationUnitCost(String contractNo,Model model) {
		List<StyleOptionEntity> contractList = customizationUnitCostService.findContractInfo();
		model.addAttribute("contractList",contractList);
		model.addAttribute("contractNo",contractNo);
		return "modules/order/customizationUnitCost";
	}
    /**
     * 定制订单质检(订单检测详细)
     *
     *
     * @return
     */
	@RequiresPermissions("customization:unitcost:view")
    @RequestMapping(value = { "searchList" })
    public String searchList(StyleOptionEntity styleOptionEntity, HttpServletRequest request, HttpServletResponse response) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "unitCost");
		// 画面取得的检索项目
		Long contractID = styleOptionEntity.getContractID();
//		String insideOrderNO = styleOptionEntity.getInsideOrderNO();
//		String beginDate = styleOptionEntity.getBeginDate();
//		String endDate = styleOptionEntity.getEndDate();
		String styleNoFrom = styleOptionEntity.getStyleNoFrom();
		String styleNoTo = styleOptionEntity.getStyleNoTo();
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 拼接字符串供分页使用
		String searchParam ="&styleNoFrom="+styleNoFrom+"&styleNoTo="+styleNoTo+"&contractID="+contractID;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<StyleOptionEntity> page = customizationUnitCostService.findList(new Page<StyleOptionEntity>(request, response), styleOptionEntity);
		// 读取文件生成字符串
		String strHtml = "";
		try{
			Map<String, Object>  map = new HashedMap();
			map.put("adminUri",strUri);
			map.put("unitCosts",page.getList());
			map.put("pageNo",page.getPageNo());
			map.put("pageSize",page.getPageSize());
			map.put("springMacroRequestContext", new RequestContext (request));

			strHtml  =	FreeMarkerTemplateUtils.processTemplateIntoString(
				freemarkerConfiguration.getTemplate("customizationCostHtml.ftl"), map);
		}
		catch (Exception ex) {
		}
		listMap.put("unitCost", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}
    
    /**
     * excel上传画面迁移
     * @return
     */
    @RequestMapping(value = {"uploadExcelFile"})
    public String popupUploadExcelFile(Model model) {
    	model.addAttribute("imageName","customizationUnitCost");
        return "modules/order/uploadOrderExcelFile";
    }
    
    /**
     * 单耗明细画面
     * @return
     */
    @RequestMapping(value = {"unitDetail"})
    public String unitDetail(StyleOptionEntity styleOptionEntity,Model model) {
    	List<StyleOptionEntity> unitCostList = customizationUnitCostService.findUnitCostDetail(styleOptionEntity);
    	model.addAttribute("unitCostDetailsList",unitCostList);
        return "modules/order/customizationUnitCostDetail";
    }
    
    /**
     * 出库申请画面
     * @return
     */
    @RequestMapping(value = {"inventoryRequest"})
    public String inventoryRequest(InventoryRequestEx inventoryRequestEx,Model model) {
    	// 获取当前用户
		User curLoginUser = inventoryRequestEx.getCurrentUser();
		List<InventoryRequestEx> productionList = inventoryRequestExService.findProductionList();
		inventoryRequestEx.setProductionList(productionList);
		/*inventoryRequestEx.setInventoryRequestNo("HLOUT"+DateUtils.formatDate(new Date(), "yyMMddHHmmss"));*/
    	// 出库单条码
    	inventoryRequestEx.setStockBarCode(SequenceUtil.inventoryRequestbarcode().getReturnCode());
    	// 申请人
    	inventoryRequestEx.setRequestUser(curLoginUser.getFirstName() + curLoginUser.getLastName());
    	inventoryRequestEx.setRequestUserId(curLoginUser.getId());
    	// 申请日期
    	inventoryRequestEx.setRequestDate(new Date());
    				
    	// 下拉菜单（客供入库）
    	inventoryRequestEx.setInventoryCategory(ResourcesUtil.getConfig("outbound_category_produce"));
    	// 下拉合同号
    	List<StyleOptionEntity> contractList = customizationUnitCostService.findContractInfo();
		model.addAttribute("contractList",contractList);
    	model.addAttribute("imageStr","customizationUnitCost");
    	model.addAttribute("inventoryRequestEx",inventoryRequestEx);
        return "modules/material/inventoryRequestExCreate";
    }
    
    /**
     * 导入定制项目
     * @param inventoryRequestEx
     * @param response
     * @return
     */
    @RequiresPermissions("customization:unitcost:view")
    @RequestMapping(value = "getMaterialList")
    @ResponseBody
    public String getMaterialList(InventoryRequestEx inventoryRequestEx, HttpServletResponse response) {
    	List<InventoryRequestEx> materialList = customizationUnitCostService.findAllUnitCost(inventoryRequestEx);
		return renderString(response,materialList);
    }
    
    /**
     * 导入定制项目
     * @param file
     * @param response
     * @return
     */
    @RequiresPermissions("customization:unitcost:edit")
    @RequestMapping(value = "insertExcelData", method=RequestMethod.POST)
    @ResponseBody
    public String importFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response){
    	String oldFlg= "false";
    	try {
    		ImportExcel ei = new ImportExcel(file, 1, 0);
    		List<StyleOptionEntity> list = ei.getDataList(StyleOptionEntity.class);
    		customizationUnitCostService.updateExcelData(list);
    		oldFlg = "true";
    		String fileName = file.getOriginalFilename().split("定制")[0];
    		//保存成功给指定人员发送邮件
    		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + Global.getAdminPath() + "/customization/unitcost/?contractNo="+fileName;
            SendEmailMessage sendEmailMessage = new SendEmailMessage();
            sendEmailMessage.setDataTheme(ResourcesUtil.getConfig("erp_send_mail_theme03"));
            sendEmailMessage.setDataMessage(ResourcesUtil.getConfig("erp_send_mail_textMessage03"));
            sendEmailMessage.setDataXXX01(UserUtils.getUser().getFirstName()+UserUtils.getUser().getLastName());
            sendEmailMessage.setDataXXX02(fileName);
            sendEmailMessage.setDataXURLX(url);
            sendEmailMessage.setDataYYMMDD01(DateUtils.formatDate(new Date(), "yyyy-MM-dd").toString());
            sendEmailMessage.setDataXXX02(fileName);
            //发送邮件
            UserUtils.sendEmail(sendEmailMessage);

		} catch (Exception e) {
    		// 记录日志
            logger.error (e.getMessage (), e);
			return renderString(response,oldFlg);
		}
    	return renderString(response,oldFlg);
    }

	
}
